<template>
  <base-container>
    <!-- 订单列表头部 -->
    <OrderListHeader
      :initial-rental-type="rentalType"
      :initial-order-switch="orderSwitchEnabled"
      @rental-type-change="handleRentalTypeChange"
      @order-switch-change="handleOrderSwitchChange"
      @set-business-hours="handleSetBusinessHours"
    />

    <!-- Tab 栏 -->
    <OrderTabBar
      :tabs="tabsForView"
      :active-tab="activeTab"
      @tab-change="handleTabChange"
      @batch-dispatch="handleBatchDispatch"
      @order-assignment="handleOrderAssignment"
    />

    <!-- 搜索栏 -->
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />

    <!-- 列表容器（先留空，后面接入卡片列表即可） -->
    <base-table-card />
  </base-container>
</template>

<script setup>
  import { ref, computed } from "vue";
  import Option from "@/crudOption/order/orderList";
  import OrderListHeader from "./components/OrderListHeader.vue";
  import OrderTabBar from "./components/OrderTabBar.vue";

  // ===== 搜索配置 =====
  const { searchOption } = Option();
  const searchParams = ref({});

  // ===== 顶部头部区状态 =====
  const rentalType = ref("all");
  const orderSwitchEnabled = ref(true);

  // ===== Tab 激活态 =====
  const activeTab = ref("all");

  // ===== Tab 数据（原始） —— 去重前 =====
  const rawTabs = ref([
    { key: "all", label: "全部", count: 552 },
    { key: "pending_payment", label: "待支付", count: 552 },
    { key: "pending_dispatch", label: "待派单", count: 5 },
    { key: "pending_review", label: "待审核", count: 552 },
    { key: "rejected", label: "已拒单", count: 552 },
    { key: "pending_shipment", label: "待发货", count: 552 },
    { key: "pending_receipt", label: "待收货", count: 552 },
    // { key: "pending_settlement", label: "待结算", count: 6 },
    // { key: "completed", label: "已完成", count: 5 },
    // { key: "closed", label: "已关闭", count: 2 },
    // { key: "refunding", label: "退款中", count: 12 },
    // { key: "refunded", label: "已退款", count: 8 },
    // { key: "cancelled", label: "已取消", count: 15 },
    // { key: "expired", label: "已过期", count: 3 },
    // { key: "suspended", label: "已暂停", count: 7 },
    // { key: "resumed", label: "已恢复", count: 4 },
    // { key: "extended", label: "已延期", count: 9 },
    // { key: "terminated", label: "已终止", count: 6 },
    // { key: "archived", label: "已归档", count: 25 },
    // { key: "deleted", label: "已删除", count: 1 },

    // // 新增其他状态
    // { key: "pending_confirmation", label: "待确认", count: 18 },
    // { key: "confirmed", label: "已确认", count: 42 },
    // { key: "in_transit", label: "运输中", count: 28 },
    // { key: "delivered", label: "已送达", count: 156 },
  ]);

  // ===== 供组件渲染用的 Tab 列表：去重 + 过滤（可选过滤 count=0） =====
  const tabsForView = computed(() => {
    const map = new Map();
    rawTabs.value.forEach(t => {
      if (!map.has(t.key))
        map.set(t.key, t); // 去重，保留第一项
      else {
        // 如需合并重复项计数，可改为：
        // const old = map.get(t.key); map.set(t.key, { ...old, count: old.count + t.count })
      }
    });
    // 如需隐藏 count === 0 的项：return [...map.values()].filter(t => t.count > 0)
    return [...map.values()];
  });

  // ===== 搜索动作 =====
  const loadTableSearch = () => {
    // 结合 Tab & 头部状态一起查询
    const query = {
      ...searchParams.value,
      tab: activeTab.value,
      rentalType: rentalType.value,
      orderSwitchEnabled: orderSwitchEnabled.value,
    };
    console.log("搜索参数:", query);
    // TODO: 调订单列表接口，返回后刷新列表 + 计数
    // const { list, counters } = await Api.order.search(query)
    // updateTabCounters(counters)
  };

  const loadTableSearchReset = () => {
    searchParams.value = {};
    loadTableSearch();
  };

  // ===== 事件处理（头部） =====
  const handleRentalTypeChange = type => {
    rentalType.value = type;
    loadTableSearch();
  };
  const handleOrderSwitchChange = enabled => {
    orderSwitchEnabled.value = enabled;
    loadTableSearch();
  };
  const handleSetBusinessHours = () => {
    // 打开营业时间设置弹窗
    console.log("打开营业时间设置");
  };

  // ===== 事件处理（Tab） =====
  const handleTabChange = key => {
    activeTab.value = key;
    loadTableSearch();
  };
  const handleBatchDispatch = () => {
    console.log("批量派单");
    // 打开批量派单弹窗…
  };
  const handleOrderAssignment = () => {
    console.log("订单分配");
    // 打开订单分配弹窗…
  };

  // ===== 动态更新计数（当你拉完聚合接口 counters 后调用它） =====
  // eslint-disable-next-line no-unused-vars
  function updateTabCounters(counters = {}) {
    // counters 形如：{ all: 552, pending_payment: 66, ... }
    rawTabs.value = rawTabs.value.map(t => ({
      ...t,
      count: counters[t.key] ?? t.count,
    }));
    // 如果当前激活的 tab 被后台“隐藏”（count 可能为 0 但你选择过滤），兜底回到 all
    const keys = new Set(tabsForView.value.map(t => t.key));
    if (!keys.has(activeTab.value)) activeTab.value = "all";
  }
</script>
